﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;

namespace Willow.MVC.Result
{
    public class ExportWordResult : ActionResult
    {
        public string FileName { get; set; }
        public string TemplatePath { get; set; }
        public Dictionary<string, string> PlaceHolders { get; set; }

        public ExportWordResult(string fileName, string templatePath, Dictionary<string, string> placeholders)
        {
            this.FileName = fileName;
            this.TemplatePath = templatePath;
            this.PlaceHolders = placeholders;
        }

        public override void ExecuteResult(ControllerContext context)
        {
            SetResponse(context);
        }

        /// <summary>
        /// 描述：设置并向客户端发送请求响应
        /// <param name="context">The context.</param>
        private void SetResponse(ControllerContext context)
        {

            FileName = HttpUtility.UrlEncode(Encoding.UTF8.GetBytes(FileName));

            byte[] content = GetContent();

            context.HttpContext.Response.Clear();
            context.HttpContext.Response.ClearContent();
            context.HttpContext.Response.Buffer = true;
            context.HttpContext.Response.Charset = "UTF8";
            context.HttpContext.Response.ContentEncoding = Encoding.UTF8;
            context.HttpContext.Response.ContentType = "application/ms-word";
            context.HttpContext.Response.AddHeader("Content-Disposition", "attachment; filename=" + FileName + ".doc");
            context.HttpContext.Response.AddHeader("Content-Length", content.Length.ToString());
            context.HttpContext.Response.BinaryWrite(content);
            context.HttpContext.Response.End();
        }

        /// <summary>
        /// 读取模板内容
        /// </summary>
        /// <returns></returns>
        private byte[] GetContent()
        {
            string content = File.ReadAllText(TemplatePath);
            foreach (var item in PlaceHolders)
            {
                content = content.Replace("{" + item.Key + "}", item.Value);
            }
            return Encoding.UTF8.GetBytes(content);
        }


    }
}
